﻿using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class ParameterRule : ILRule<ParameterHandle>
    {
        [ILInfo(true)]
        public string Name { get; }

        [ILInfo]
        public ParameterAttributes Attributes { get; }

        [ILInfo(true)]
        public int SequenceNumber { get; private set; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public CustomAttributeHandleCollection CustomAttributes { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandle)]
        public ConstantHandle DefaultValue { get; }

        public BlobHandle MarshallingDescriptor { get; }

        public ParameterRule(
            ParameterAttributes attributes,
            string name)
            : base()
        {
            Attributes = attributes;
            Name = name;
        }

        public ParameterRule(MetadataReader reader, ParameterHandle parameterHandle)
            : base(reader)
        {
            Parameter parameter = reader.GetParameter(parameterHandle);
            Attributes = parameter.Attributes;
            Name = reader.GetString(parameter.Name);
            SequenceNumber = parameter.SequenceNumber;
            CustomAttributes = parameter.GetCustomAttributes();
            DefaultValue = parameter.GetDefaultValue();
            MarshallingDescriptor = parameter.GetMarshallingDescriptor();
        }

        public override ParameterHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            SequenceNumber = designer.ParameterCounter.Increment();
            ParameterHandle parameterHandle = builder.AddParameter(
                attributes: Attributes,
                name: Name == null ? default : builder.GetOrAddString(Name),
                sequenceNumber: SequenceNumber);
            designer.ParameterNumber.Increment();
            return parameterHandle;
        }
    }
}